// ==UserScript==
// @name         起点- 最近更新
// @namespace    https://www.qidian.com/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      https://www.qidian.com/*
// @icon         https://www.google.com/s2/favicons?domain=qidian.com
// ==/UserScript==

(function () {
    'use strict';

    class Local {
        constructor(key) {
            this.key = key;
            this.initLo();
        }
        setData(key, value) { // 保存键值对到本地
            if (typeof value === 'undefined') {
                return localStorage.setItem(this.key, JSON.stringify(key));
            }
            if (typeof value === 'string') {
                return localStorage.setItem(key, value);
            }
            try {
                localStorage.setItem(key, JSON.stringify(value));
            } catch (err) {
                return err;
            }
        }
        getData(key) { // 获取指定key的数据
            const value = localStorage.getItem(key || this.key);
            try {
                return JSON.parse(value);
            } catch (err) {
                return value;
            }
        }
        removeData(key) { // 删除指定key的数据
            return localStorage.removeItem(key);
        }
        clearData() { // 删除所有的本地数据
            return localStorage.clear();
        }
        initLo() { // 初始化
            if (!window.localStorage) {
                throw new Error("浏览器不支持 localstorage 本地存储！！！")
            }
        }
    }

    (function local(local = 'local') {
        var local_ = local;
        if (window[local]) return console.log('属性名重复！！');
        try {
            window[local_] = new Local(local);
            console.log('封装本地存储成功，可以直接使用 ' + local_ + ' 对象来操作本地存储数据！')
        } catch (err) {
            console.log(err)
            return err;
        }
    })("db")

    if (!db.getData('start')) return;

    let forTime = setInterval(() => {
        fetch('https://www.qidian.com/').then((res) => {
            return res.text();
        }).then((res) => {
            window.aa = $(res)
            // debugger
            let tr = aa.find('.update-table.all tr');
            let dbData = db.getData();
            let showList = [];
            for (let index = 0; index < tr.length; index++) {
                // td = $(tr[index]).find('td');
                let td = tr[index].querySelectorAll('td');
                let content = {
                    type: td[0].innerText.trim(),
                    name: td[1].innerText.trim(),
                    href: td[1].querySelector('a').href,
                    node: td[2].innerText.trim(),
                    author: td[3].innerText.trim(),
                }
                dbData[content.name] = content;
                showList.push(content);
            }
            db.setData(dbData);
            console.log('搜索结果：', showList)
        })
    }, 1000 * 30);


    console.log('', window)
    // window.$ = window.unsafeWindow.$;
    // window.unsafeWindow.$ = window
    setTimeout(() => {
        // console.log('', window.unsafeWindow.$)
        // window.$ = window.unsafeWindow.$;
        Object.assign(window.unsafeWindow, fn, { db });
        window.unsafeWindow.created();
    }, 1000);

    let fn = {
        created() {
            let html = `
        <div onclick="init()"
            style="position: fixed; display: flex; height: 44px; width: 51px; top: 50%; z-index: 100; background-color: #e9e9e9; box-sizing: border-box; font-size: 16px; justify-content: center; align-items: center;">
            打开</div>
        `
            $(document.body).append(html)
        },
        init() {
            remove()
            let html = `
                    <div id="mydiv"
                        style="position: fixed; display: block; height: 100%; width: 100%; overflow-y: scroll; top: 0px; z-index: 100; background-color: #e9e9e9; padding: 20px; box-sizing: border-box;">
                        <div onclick="remove()"
                            style="position: fixed; top: 23px; right: 30px; width: 40px; height: 40px; background-color: #f32e2e; border-radius: 50%; display: flex; justify-content: center; justify-items: center; align-items: center; font-size: 36px; line-height: 1; color: #fff;">
                            x</div>
                        <div style="display: block; text-align: center; height: 46px;">
                            <input type="text" id="input1" onchange="search()"
                                style="height: 33px; border-radius: 6px; padding: 5px 10px; font-size: 20px;">
                            <input type="button" value="搜索" onclick="search()"
                                style="font-size: 20px; background-color: #977a7a; padding: 5px 10px; border-radius: 6px;">
                        </div>
                        <table id="table1" style="width: 100%; padding: 26px 43px;margin: 10px 20px;"> </table>
                    </div>
                `
            $(document.body).append(html)
            setTable(db.getData());
        },
        search() {
            let value = document.getElementById('input1').value;
            let data = {};
            let sou = db.getData();
            let wanBen = db.getData('wanBen') || {};
            Object.assign(sou, wanBen);
            // let _value = value.trim().split(/\s+/);
            let _value = value.replace(/\s*/g, '').split('');
            Object.keys(sou).filter((res) => {
                let flag = true;
                // for (let index = 0; index < _value.length; index++) res.includes(_value[index]) || (flag = false);
                _value.find((item) => { res.includes(item) || (flag = false); })
                if (flag) {
                    // console.log(res)
                    data[res] = sou[res];
                }
            })
            setTable(data);
        },
        remove() {
            let mydiv = document.getElementById('mydiv') && document.getElementById('mydiv').remove()
        },
        setTable(obj) {
            let data;
            try {
                data = JSON.parse(obj);
            } catch (e) {
                data = obj;
            }
            let html = '';
            Object.keys(data).forEach((item) => {
                let res = data[item];
                html += `<tr style="height: 55px; font-size: 22px;">
                <td><a href="${res.href}" target="_blank" style="text-decoration: none;color: #5f20f7;">${res.name}</a></td>
                <td>${res.node}</td>
                <td style="max-width:900px;padding: 10px 0;">${res.dec || res.author}</td>
                <td style="min-width: 70px;">${res.type}</td>
            </tr>`;
            })
            document.getElementById('table1').innerHTML = html;
        }
    }


    // Your code here...
})();